package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class CartInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<UserInfoTo> cache = new ThreadLocal<>();


    public static UserInfoTo getUserInfoTo() {
        return cache.get();
    }

    /**
     * 请求方法执行之前
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // session 域中获取用户信息
        HttpSession session = request.getSession();
        Map<String, Object> member = (Map<String, Object>) session.getAttribute(AuthConstant.LOGIN_USER);
        UserInfoTo info = new UserInfoTo();
        if (member != null) {
            info.setUserId(Long.valueOf(member.getOrDefault("id", "0").toString()));
        }

        // 判断Cookie
        Cookie cookie = WebUtils.getCookie(request, CartConstant.TEMP_USER_COOKIE_NAME);
        if (cookie != null) {
            info.setUserKey(cookie.getValue());
            info.setTempUser(false);
        }

        // 如果是临时用户，生成cookie
        if (info.isTempUser()) {
            String userKey = UUID.randomUUID().toString();
            info.setUserKey(userKey);
            info.setTempUser(true);
        }

        log.info("user info is {}", info);
        cache.set(info);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo info = cache.get();
        if (info.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, info.getUserKey());
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            cookie.setDomain("gulimall.com");
            response.addCookie(cookie);
        }

    }
}
